package view.commands;

import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;

import javax.imageio.ImageIO;

import view.components.ComponentsFactory;
import view.components.ErrorCatcher;
/**
 * Load image
 * @author Yin
 *
 */
public class ImageReader implements Command<String> {
    private String myLocation;
    private BufferedImage myBufferedImage;

    private static final String IMAGE_ERROR = "ImageReadingError";
    private static final String LOCATION_ERROR = "ImageLocationError";

    public ImageReader() {
        myLocation = new String();
    }

    public ImageReader(String location) {
        if (location == null)
            new ErrorCatcher(ComponentsFactory.getComponentsMap().get(
                    LOCATION_ERROR));
        else
            myLocation = location;
    }

    /**
     * Load image
     * Show error message if IO Exception is thrown
     */
    @Override
    public BufferedImage execute(String location) {

        if (location != null)
            myLocation = location;

        try {
            BufferedInputStream is = new BufferedInputStream(
                    new FileInputStream(myLocation));
            myBufferedImage = ImageIO.read(is);
        } catch (IOException ex) {
            new ErrorCatcher(ComponentsFactory.getComponentsMap().get(
                    IMAGE_ERROR));
        }

        return myBufferedImage;
    }

}
